<template>
  <a-tree-select
    v-model:modelValue="value"
    :loading="loading"
    :allow-search="allowSearch"
    :allow-clear="allowClear"
    :disabled="disable"
    :data="treeData"
    placeholder="请选择角色"
    :multiple="multiple"
    :selectable="selectable"
    :tree-check-strictly="treeCheckStrictly"
    :field-names="{
      key: 'id',
      title: 'name',
      children: 'children',
    }"
    @search="onSearch"
  ></a-tree-select>
</template>

<script lang="ts" setup>
  import { ref, computed, defineProps, defineEmits, PropType } from 'vue';
  import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import useLoading from '@/hooks/loading';
  import { findRoles } from '@/api/role';
  import tree from '@/utils/tree';

  const { loading, setLoading } = useLoading();
  const searchForm = ref({
    name: '',
    type: '',
  });
  const props = defineProps({
    modelValue: {
      type: Array as PropType<string[]>,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    // 设置可选择的节点，默认全部可选
    selectable: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    treeCheckStrictly: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    allowSearch: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    allowClear: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    disable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  });
  const emit = defineEmits(['update:modelValue', 'change']);
  const transmitList = ref();
  const value = computed({
    get() {
      return props.modelValue;
    },
    set(val) {
      emit('update:modelValue', val);
      emit(
        'change',
        props.multiple
          ? transmitList.value.filters((item: any) => val.includes(item.id))
          : transmitList.value.find((item: any) => item.id === val)
      );
    },
  });
  const treeData = ref<TreeNodeData[]>([]);
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await findRoles(searchForm.value);
      transmitList.value = data;
      treeData.value = tree.toTree(data, 'id', 'parentId');
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  const onSearch = (keys: string) => {
    searchForm.value.name = keys;
    fetchData();
  };
  fetchData();
</script>
